<template>
  <view class="main">
    <!-- 提示弹窗 -->
    <u-toast ref="uToast" />
    <u-modal
      v-model="beginShow"
      :show-title="false"
      content="开始灭火器检查"
      show-cancel-button
      @confirm="begin()"
    ></u-modal>
    <u-modal
      v-model="endShow"
      title="结束本次灭火器检查"
      content="请确认所以灭火器检查完毕再结束!"
      show-cancel-button
      confirm-text="结束"
      confirm-color="#f93534"
      @confirm="end()"
    ></u-modal>

    <!-- 导航栏 -->
    <u-navbar :is-back="false" title="灭火器检查" title-size="40"> </u-navbar>

    <!-- 开始页面 -->

    <!-- 按钮 -->
    <u-button
      class="btn"
      type="success"
      v-if="check == false"
      v-on:click="beginShow = true"
      >开始检查</u-button
    >
    <u-button
      class="btn"
      type="primary"
      v-if="check == false"
      v-on:click="tableToExcel"
      >导出数据</u-button
    >
    <p v-if="url != '' && check == false" style="font-size: 30rpx">
      导出数据文件位置：
    </p>
    <p v-if="url != '' && check == false" style="font-size: 30rpx">{{ url }}</p>

    <!-- 图标 -->
    <view v-if="check == false" style="text-align: center; margin-top: 200rpx">
      <u-icon name="android-fill" size="500" @click="click"></u-icon>
    </view>

    <!-- 检查过程页面 -->

    <!-- 按钮 -->
	<u-grid :col="2" v-if="check == true" style="position: fixed; top: 150rpx; height: 150rpx; z-index: 999;">
      <u-grid-item v-on:click="scan">
        <u-icon name="scan" :size="46"></u-icon>
        <view class="grid-text">扫描</view>
      </u-grid-item>
      <u-grid-item v-on:click="endShow = true">
        <u-icon name="pause" :size="46"></u-icon>
        <view class="grid-text">结束检查</view>
      </u-grid-item>
    </u-grid>

    <!-- 灭火器信检查弹窗 -->
    <u-modal
      v-model="checkShow"
      title="灭火器检查"
      :show-cancel-button="true"
      @confirm="checkSubmit"
    >
      <u-form class="form">
        <u-form-item
          label="灭火器编号："
          prop="id"
          label-width="225rpx"
          label-align="right"
        >
          <u-input
            v-model="form.id"
            type="number"
            maxlength="5"
            placeholder="请输入灭火器编号"
            disabled
          />
        </u-form-item>
        <u-form-item
          label="地点信息："
          prop="location"
          label-width="200rpx"
          label-align="right"
        >
          <u-input
            v-model="form.location"
            placeholder="请输入地点信息"
            style="line-height: 5rpx"
            disabled
          />
        </u-form-item>
        <u-form-item
          label="状态："
          prop="status"
          label-width="150rpx"
          label-align="right"
        >
          <u-radio-group v-model="form.status">
            <u-radio
              v-for="(item, index) in status"
              :key="index"
              :name="item.name"
            >
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item
          label="备注："
          prop="other"
          label-width="150rpx"
          label-align="right"
        >
          <u-input v-model="form.other" placeholder="没有补充的信息" />
        </u-form-item>
      </u-form>
    </u-modal>

	<view style="margin-top: 140rpx; padding-bottom: 30rpx;">
		<!-- 灭火器信息列表 -->
		<u-swipe-action
		  v-if="check == true"
		  class="info"
		  :show="info.show"
		  :index="index"
		  v-for="(info, index) in info_list"
		  :key="info.id"
		  @click="click"
		  
		>
		  <view class="infodetail">
		    <p class="title">{{ info_title.id }}:</p>
		    <p class="content">{{ info.id }}</p>
		  </view>
		  <view class="infodetail">
		    <p class="title">{{ info_title.location }}:</p>
		    <p class="content">{{ info.location | ellipsis }}</p>
		  </view>
		  <view class="infodetail">
		    <p class="title">{{ info_title.status }}:</p>
		    <p class="content">{{ info.status }}</p>
		  </view>
		  <view class="infodetail">
		    <p class="title">{{ info_title.other }}:</p>
		    <p class="content">{{ info.other | ellipsis }}</p>
		  </view>
		  <view class="infodetail">
		    <p class="title">{{ info_title.check }}:</p>
		    <p
		      class="content"
		      :class="[
		        info.check == '待检查' ? 'color-red' : '',
		        info.check == '已检查' ? 'color-green' : '',
		      ]"
		    >
		      {{ info.check | ellipsis }}
		    </p>
		  </view>
		  <view class="infodetail">
		    <p class="title">{{ info_title.time }}:</p>
		    <p class="content">{{ info.time | ellipsisTime }}</p>
		  </view>
		</u-swipe-action>
		
		<u-divider
		    v-if="check == true"
		    half-width="200"
		    margin-top="180"
		    margin-bottom="30"
		    >没有更多数据了</u-divider
		  >
		
		  <view style="text-align: center; font-size: 2rpx; color: #c1bebf;"
		    >作者：AICHI</view
		  >
		</view>
	</view>
    
</template>

<script>
import { selectCheckSet, checkSet } from "@/api/sys";
import {
  selectInfo,
  beginCheck,
  endCheck,
  selectInfoById,
  updateInfo,
} from "@/api/info";
import { formatNumber, formatDateThis, getUnixTime, dateFormat } from "@/api/dateUtil.js";
var that;
export default {
  data() {
    return {
      check: false,
			show: false,
      beginShow: false,
      endShow: false,
      checkShow: false,
      url: "",
      value1: null,
      options1: [
        {
          label: "默认排序",
        },
      ],
      info_title: {
        id: "编号",
        location: "地点信息",
        status: "状态",
        other: "备注",
        check: "进度",
        time: "最近检查时间",
      },
      form: {
        id: "",
        location: "",
        status: "正常",
        other: "",
        time: "",
        check: "",
      },
      status: [
        {
          name: "正常",
        },
        {
          name: "故障",
        },
        {
          name: "其他",
        },
      ],
      info_list: [],
    };
  },
  filters: {
    ellipsis(value) {
      if (!value || value == "undefined") return "无";
      if (value.length > 12) {
        return value.slice(0, 12) + "...";
      }
      return value;
    },
    ellipsisTime(value) {
      if (!value || value == "undefined") return "";
      return value;
    },
  },
  methods: {
    // 开始检查
    begin() {
      beginCheck();
      checkSet("1");
      (this.url = ""), (this.check = true);
      this.getInfo();
    },
    // 结束检查
    end() {
	  // 设置检查标志位
      checkSet("0");
      this.check = false;
    },
    // 获取检查灭火器信息
    getInfo() {
      selectInfo().then(function (data) {
        that.info_list = data;
		console.log(that.info_list)
      });
    },
    // 扫描灭火器
    scan() {
      uni.scanCode({
        success: function (res) {
          // console.log('条码类型：' + res.scanType);
          // console.log('条码内容：' + res.result);
          selectInfoById(res.result).then(function (data) {
            if (that.isEmptyObject(data)) {
              that.$refs.uToast.show({
                title: "获取不到灭火器信息!",
                type: "error",
              });
            } else {
              that.form = JSON.parse(JSON.stringify(data[0]));
              that.checkShow = true;
            }
          });
        },
      });
    },
    // 检查完毕 确认
    checkSubmit() {
      // 设置时间
      let date = new Date();
      this.form.time = dateFormat("YYYY-mm-dd HH:MM", date);
      // 设置进度
      this.form.check = "已检查";
      updateInfo(this.form);
      this.getInfo();
    },
    // 机器人互动
    click() {
      this.$refs.uToast.show({
        title: "我是机器人AICHI,很高兴为你服务!",
        type: "success",
        icon: false,
      });
    },
    // 判断json数据是否为空
    isEmptyObject(obj) {
      for (var key in obj) {
        return false;
      }
      return true;
    },
    tableToExcel() {
      // endCheck();
      selectInfo().then(function (data) {
        //列标题
        let worksheet = "sheet1";
        let str =
          "<tr><td>编号</td><td>地点信息</td><td>状态</td><td>备注</td><td>时间</td><td>进度</td></tr>";
        //循环遍历，每行加入tr标签，每个单元格加td标签
        for (let i = 0; i < data.length; i++) {
          str += "<tr>";
          for (let item in data[i]) {
            //增加\t为了不让表格显示科学计数法或者其他格式
            str += `<td>${data[i][item] + "\t"}</td>`;
          }
          str += "</tr>";
        }
        //下载的表格模板数据
        let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
						xmlns:x="urn:schemas-microsoft-com:office:excel" 
						xmlns="http://www.w3.org/TR/REC-html40">
						<head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
						<x:Name>${worksheet}</x:Name>
						<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
						</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
						</head><body><table>${str}</table></body></html>`;
        //下载模板
        exportFile(template);
      });
    },
  },
  created() {
    // 初始化
    selectCheckSet().then(function (data) {
      switch (data) {
        case "0":
          that.check = false;
          break;
        case "1":
          that.check = true;
          that.getInfo();
          break;
      }
    });
  },
  onLoad() {
    that = this;
  },
};

function exportFile(fileData, documentName = "灭火器信息") {
  /*
			PRIVATE_DOC: 应用私有文档目录常量
			PUBLIC_DOCUMENTS: 程序公用文档目录常量
			*/
  plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function (fs) {
    let rootObj = fs.root;
    let fullPath = rootObj.fullPath;
    // let reader = rootObj.createReader();
    // console.log(reader);
    // reader.readEntries((res)=>{
    //     console.log(res); //这里拿到了该目录下所有直接文件和目录
    // },(err)=>{console.log(err);})

    console.log("开始导出数据********");
    // 创建文件夹
    rootObj.getDirectory(
      documentName,
      {
        create: true,
      },
      function (dirEntry) {
        //获取当前的年月继续创建文件夹
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        dirEntry.getDirectory(
          `${year}年${month}月${day}日`,
          {
            create: true,
          },
          function (dirEntry2) {
            // 创建文件,防止重名
            let fileName =
              "灭火器检查数据" + getUnixTime(formatDateThis(new Date()));
            console.log(fileName);
            dirEntry2.getFile(
              `${fileName}.xlsx`,
              {
                create: true,
              },
              function (fileEntry) {
                fileEntry.createWriter(
                  function (writer) {
                    writer.onwritestart = (e) => {
                      uni.showLoading({
                        title: "正在导出",
                        mask: true,
                      });
                    };

                    //  /storage/emulated/0指的就是系统路径
                    let pathStr = fullPath.replace("/storage/emulated/0", "");
                    writer.onwrite = (e) => {
                      // 成功导出数据;
                      // uni.hideLoading();
                      setTimeout(() => {
                        uni.showToast({
                          title: "成功导出",
                          icon: "success",
                        });
                        that.url = `${pathStr}${documentName}/${year}年${month}月${day}日`;
                        console.log(
                          `文件位置：${pathStr}${documentName}/${year}年${month}月${day}日`
                        );
                      }, 500);
                    };
                    // 写入内容;
                    writer.write(fileData);
                  },
                  function (e) {
                    console.log(e.message);
                  }
                );
              }
            );
          }
        );
      }
    );
  });
}
</script>

<style lang="less">
.main {
  font-size: 40rpx;

  .btn {
    margin-top: 2rpx;
    border-radius: 0rpx;
  }

  .slot-wrap {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
  }

  .info {
    background-color: #f3f4f6;
    padding: 15rpx 0;

    .infodetail {
      .title {
        color: #606266;
        display: inline;
        margin-left: 30rpx;
      }

      .content {
        color: #606266;
        display: inline;
        margin-left: 25rpx;
      }

      .color-green {
        color: #19be6b;
      }

      .color-red {
        color: #fa3534;
      }

      .color-yellow {
        color: #ff9900;
      }
    }
  }
}
</style>
